<template>
  <template v-if="cMode === 'design'">
    <el-input  disabled v-bind="$props" v-model="val" />
  </template>
  <template v-else-if="cMode === 'edit'">
    <el-input  v-show="props.runShow" v-bind="$props" v-model="val" />
  </template>
  <template v-else-if="cMode === 'read' ">
    <span  v-show="props.runShow" v-text="val"></span>
  </template>
  <template v-else-if="cMode === 'hidden' ">
    <span v-show="false" v-text="val"></span>
  </template>
</template>

<script lang="ts" setup>
import { ElInput } from 'element-plus'
import {computed, inject, nextTick, onMounted, onUnmounted, ref, watch} from "vue";
import { formModeKey } from "@/components/form/state.key";
import eventBus from '@/event/eventBus';
import {resetKey,setValueKey} from "@/config/app.keys";
import { vFormSchemeKey } from '@/components/form/state.key';


const formScheme = inject(vFormSchemeKey)!

interface Props {
  mode?: FormFieldMode
  placeholder:  string,
  clearable: boolean,
  showWordLimit: boolean,
  autofocus: boolean,
  validateEvent: boolean,
  style:  object,
  runShow:boolean,
  value?: string,
  defaultValue?: string,
  id?:string
}

interface Emits {
  (e: 'update:value', v: string): void
}

const props = defineProps<Props>()

const emits = defineEmits<Emits>()
const value1 = ref('')
const val = computed<string>({
  get: () => {
    if (props.value) {
      return props.value
    }
    if (props.defaultValue) {
      nextTick(() => emits('update:value', props.defaultValue))
      return props.defaultValue
    }
    return ''
  },
  set: v => emits('update:value', v)
})

const formMode = inject(formModeKey)
const cMode = computed<FormFieldMode>(() => {
  if (props.mode) {
    return props.mode
  }
  if (formMode?.value) {
    return formMode.value
  }
  return "edit"
})
watch(() => props.value, () => {
  value1.value = props.value
  // if(value1.value!=val.value){
  //   val.value = value1.value
  // }
},{immediate: true})
onMounted(() =>{
  //debugger;
  console.log('TextInput props :'+JSON.stringify(props));
  // bus.on(props.id+"_"+resetKey,() => {
  //   val.value = ""
  // })
  // bus.on(props.id+"_"+setValueKey,(data) => {
  //   console.log('TextInput setValueKey :'+JSON.stringify(data));
  //   val.value = data.toString()
  // })

  eventBus.$on(props.id+"_"+resetKey,() => {
    val.value = ""
  })
  eventBus.$on(props.id+"_"+setValueKey,(data) => {
    console.log('TextInput setValueKey :'+JSON.stringify(data));
    val.value = data.toString()
    // if(value1.value!=val.value) {
    //   val.value = value1.value
    // }
  })
})
onUnmounted(() =>{
  // bus.off(props.id+"_"+resetKey);
  // bus.off(props.id+"_"+setValueKey);
  eventBus.$off(props.id+"_"+resetKey);
  eventBus.$off(props.id+"_"+setValueKey);
})
// console.log('TextInput props :'+JSON.stringify(props));
</script>

<style scoped>

</style>
